//
//  FirstRecoViewController.m
//  BreadTravel
//
//  Created by 张健 on 15/12/22.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "FirstRecoViewController.h"
#import "ZJScrollModel.h"
#import "ZJElementsModel.h"
#import "StoryDetailViewController.h"
#import "LRJRecSecTraViewController.h"
#import "ZJRecFirstStoryTableViewCell.h"
#import "ZJRecFirstTravelTableViewCell.h"
#import "ZJRecFirstAdvertTableViewCell.h"
#import "WebViewControllerCJT.h"
#import "ZJFirstRecMoreStoryViewController.h"

@interface FirstRecoViewController ()<UITableViewDataSource,UITableViewDelegate,ZJRecFirstStoryTableViewCell,SDCycleScrollViewDelegate>

@property(nonatomic,strong)UITableView *myTableView;

@property(nonatomic,strong)UISearchController *searchController;
@property(nonatomic,strong)NSMutableArray *eleArray;
@property(nonatomic,strong)NSMutableArray *scrollArray;
@property(nonatomic,strong)UIPageControl *pageC;
@property(nonatomic,strong)SDCycleScrollView *cycleScrollView2;
@property(nonatomic, copy)NSString *imageURL;

@end

@implementation FirstRecoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 15, 50, 20)];
    titleLabel.text = @"乐在途中";
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    self.myTableView = [[UITableView alloc]initWithFrame:[[UIScreen mainScreen] bounds] style:UITableViewStylePlain];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
//    [self.myTableView mas_updateConstraints:^(MASConstraintMaker *make) {
//        
//        make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
//    }];
    [self.view addSubview:self.myTableView];
    
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.myTableView registerClass:[ZJRecFirstStoryTableViewCell class] forCellReuseIdentifier:@"ZJRecFirstStoryTableViewCell"];
    [self.myTableView registerClass:[ZJRecFirstTravelTableViewCell class] forCellReuseIdentifier:@"ZJRecFirstTravelTableViewCell"];
    [self.myTableView registerClass:[ZJRecFirstAdvertTableViewCell class] forCellReuseIdentifier:@"ZJRecFirstAdvertTableViewCell"];
    
    self.myTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 进入刷新状态后会自动调用这个block
    }];
    
    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadNewData方法）
    self.myTableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    // 马上进入刷新状态
    [self.myTableView.header beginRefreshing];
    
//#pragma mark - 上啦加载
//    self.myTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
//        // 进入刷新状态后会自动调用这个block
//    }];
//    
//    // 设置回调（一旦进入刷新状态，就调用target的action，也就是调用self的loadMoreData方法）
//    self.myTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
#pragma mark - 数组初始化
    self.eleArray = [NSMutableArray array];
    self.scrollArray = [NSMutableArray array];

    self.isUpLoading = NO;
    
}

- (void)loadNewData{
    
    MBProgressHUD *hub = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [hub show:YES];
    hub.labelText = @"加载中";
    [AFNetworkTool getUrl:@"http://api.breadtrip.com/v2/index/" body:nil result:HXJSON headerFile:nil success:^(id result) {
        
        self.eleArray = [NSMutableArray array];
        self.scrollArray = [NSMutableArray array];
#pragma mark scrollView的数据解析
        NSMutableDictionary *dic = result[@"data"];
        self.next_start = dic[@"next_start"];
        NSMutableArray *array = dic[@"elements"];
        //轮播图的数据
        NSMutableDictionary *firstDic = [array objectAtIndex:0];
        NSMutableArray *firstArray = firstDic[@"data"];
        NSMutableArray *secondArray = [firstArray objectAtIndex:0];
        //遍历数组
        NSMutableArray *picArray = [NSMutableArray array];
        for (NSMutableDictionary *dic in secondArray) {
            ZJScrollModel *scrollModel = [ZJScrollModel modelWithDictionary:dic];
            [picArray addObject:scrollModel.image_url];
            [self.scrollArray addObject:scrollModel];
        }
        
        
        SDCycleScrollView *cycleScrollView2 = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, WIDTH, 190) imageURLStringsGroup:picArray]; // 模拟网络延时情景
        cycleScrollView2.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
        cycleScrollView2.delegate = self;
        cycleScrollView2.dotColor = [UIColor whiteColor]; // 自定义分页控件小圆标颜色
        cycleScrollView2.placeholderImage = IMAGE;
        self.myTableView.tableHeaderView = cycleScrollView2;
        
        //             --- 模拟加载延迟
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            cycleScrollView2.imageURLStringsGroup = picArray;
        });
        
        
#pragma mark tableView的数据解析
        NSMutableArray *tableArr = [NSMutableArray arrayWithArray:array];
        if (tableArr.count == 0) {
            
        }else{
            [tableArr removeObjectAtIndex:0];
        }
        
        for (NSMutableDictionary *dic in tableArr) {
            ZJElementsModel *eleModel = [ZJElementsModel modelWithDictionary:dic];
            [self.eleArray addObject:eleModel];
        }
        
        [self.myTableView.header endRefreshing];
        [self.myTableView reloadData];
        [hub hide:YES];
        
    } failure:^(NSError *error) {
        
        
    }];
    
}

- (void)loadMoreData{
    
    NSString *url_string = [NSString stringWithFormat:@"http://api.breadtrip.com/v2/index/?next_start=%@",self.next_start];
    [AFNetworkTool getUrl:url_string body:nil result:HXJSON headerFile:nil success:^(id result) {
        
        NSMutableDictionary *dic = result[@"data"];
        self.next_start = [dic objectForKey:@"next_start"];
        NSMutableArray *array = [dic objectForKey:@"elements"];
        
        if (self.isUpLoading == NO) {
            //说明是下拉，就要清空数组中的数据
            [self.eleArray removeAllObjects];
        }
#warning mark - tableView的数据解析
        NSMutableArray *tableArr = [NSMutableArray arrayWithArray:array];
        [tableArr removeObjectAtIndex:0];
        for (NSMutableDictionary *dic in tableArr) {
            ZJElementsModel *eleModel = [ZJElementsModel modelWithDictionary:dic];
            [self.eleArray addObject:eleModel];
        }
        
        
        [self.myTableView.footer endRefreshing];
        [self.myTableView reloadData];
        
    } failure:^(NSError *error) {
        
        
    }];


}

#pragma mark - 多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.eleArray.count-3;
}
#pragma mark 行内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ZJElementsModel *eleModel = [self.eleArray objectAtIndex:indexPath.row];
    
    //把1-4的数据取出来
    NSMutableArray *array = [NSMutableArray new];
    for (int i = 1; i < 5; i++) {
        ZJElementsModel *eleModel = [self.eleArray objectAtIndex:i];
        ZJTableModel *tableModel = eleModel.tableModel;
        [array addObject:tableModel];
        
    }
    
    
    if (indexPath.row == 0 || indexPath.row == 2) {
        static NSString *cellID = @"cell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

        if (indexPath.row == 0) {
            cell.textLabel.text = eleModel.tableModel.title;
            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setTitle:@"全部 >" forState:UIControlStateNormal];
            [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
            [button addTarget:self action:@selector(buttonAction) forControlEvents:UIControlEventTouchUpInside];
            [cell.contentView addSubview:button];
            [button mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.right.mas_equalTo(0);
                make.width.mas_equalTo(70);
                make.top.mas_equalTo(4);
            }];
        }
        if (indexPath.row == 2) {
            ZJElementsModel *eleModel = [self.eleArray objectAtIndex:indexPath.row +3];
            cell.textLabel.text = eleModel.tableModel.title;
        }
        return cell;
    }else if (indexPath.row == 1){
        
        static NSString *cellID = @"ZJRecFirstStoryTableViewCell";
        ZJRecFirstStoryTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        cell.myDelegate = self;
        cell.array = array;
        
        return cell;
        
    }else if ([[[self.eleArray objectAtIndex:indexPath.row+3] desc]isEqualToString:@"推荐旅行产品"]){
        
        static NSString *cellID = @"ZJRecFirstAdvertTableViewCell";
        ZJRecFirstAdvertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];

        ZJElementsModel *eleModel = [self.eleArray objectAtIndex:indexPath.row+3];
        ZJTableModel *tableModel = eleModel.tableModel;
        cell.tableModel = tableModel;
        
        return cell;
    }else{
    
        static NSString *cellID = @"ZJRecFirstTravelTableViewCell";
        ZJRecFirstTravelTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        ZJElementsModel *eleModel = [self.eleArray objectAtIndex:indexPath.row+3];
        ZJTableModel *tableModel = eleModel.tableModel;
        cell.tableModel = tableModel;
        return cell;
        
    }
    
}


#pragma mark 点击cell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    //取消置灰效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    ZJElementsModel *eleModel = [self.eleArray objectAtIndex:indexPath.row+3];
    ZJTableModel *tableModel = eleModel.tableModel;
    
    if ([[[self.eleArray objectAtIndex:indexPath.row+3] desc]isEqualToString:@"推荐旅行产品"]){
        //广告
        WebViewControllerCJT *webVC =[[WebViewControllerCJT alloc]init];
        [self.navigationController pushViewController:webVC animated:YES];
        webVC.webURL = tableModel.url;
        
    }else if(indexPath.row != 0 && indexPath.row != 2){
        //游记详情
        LRJRecSecTraViewController *travelVC = [[LRJRecSecTraViewController alloc]init];
        [self.navigationController pushViewController:travelVC animated:YES];
        travelVC.id = tableModel.id;
    }
    
}

#pragma mark 点击轮播图
- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index{
    
    WebViewControllerCJT *webVC =[[WebViewControllerCJT alloc]init];
    [self.navigationController pushViewController:webVC animated:YES];
    webVC.webURL = [[self.scrollArray objectAtIndex:index] html_url];
}


#pragma mark 行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        return 40;
    }else if (indexPath.row == 1) {
        return 420;
    }else if (indexPath.row == 2){
        return 40;
    }
    else{
        return 200;
    }
    
}
#pragma mark 故事详情跳转
-(void)delegateFunction:(NSString *)string{
    
    StoryDetailViewController *storyDVC = [[StoryDetailViewController alloc]init];
    [self.navigationController pushViewController:storyDVC animated:NO];
    storyDVC.urlStr = string;
    storyDVC.imageURL = self.imageURL;
}

#pragma mark 点击全部按钮
- (void)buttonAction{
    
    ZJFirstRecMoreStoryViewController *moreVC = [[ZJFirstRecMoreStoryViewController alloc]init];
    [self.navigationController pushViewController:moreVC animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
